package com.seezoon.domain.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.seezoon.domain.dao.mapper.DeviceStatusHistoryMapper;
import com.seezoon.domain.dao.mapper.DeviceStatusMapper;
import com.seezoon.domain.dao.po.DeviceStatusPO;
import com.seezoon.domain.valueobj.StatusVO;
import com.seezoon.infrastructure.constants.Constants;
import com.seezoon.infrastructure.exception.Assertion;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.time.Instant;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

@Slf4j
@Service
@RequiredArgsConstructor
@Validated
public class DeviceStatusService {

    private final DeviceStatusMapper deviceStatusMapper;
    private final DeviceStatusHistoryMapper deviceStatusHistoryMapper;

    public int insert(@NotNull StatusVO statusVO) {
        DeviceStatusPO deviceStatusPO = new DeviceStatusPO();
        deviceStatusPO.setDeviceId(statusVO.getDeviceId());
        deviceStatusPO.setLatitude(statusVO.getLatitude());
        deviceStatusPO.setLongitude(statusVO.getLongitude());
        deviceStatusPO.setSpeed(statusVO.getSpeed());
        deviceStatusPO.setDirection(statusVO.getDirection());
        deviceStatusPO.setAltitude(statusVO.getAltitude());
        deviceStatusPO.setBatteryLevel(statusVO.getBatteryLevel());
        deviceStatusPO.setAlarmSignals(statusVO.getAlarmSignals());
        deviceStatusPO.setStatusFlags(statusVO.getStatusFlags());
        deviceStatusPO.setMileage(statusVO.getMileage());
        deviceStatusPO.setStatusTime(statusVO.getStatusTime());
        deviceStatusPO.setCreateTime(Instant.now());
        deviceStatusPO.setUpdateTime(Instant.now());
        int affectedRows = deviceStatusMapper.insert(deviceStatusPO);
        Assertion.affectedOne(affectedRows);
        return affectedRows;
    }

    public int update(@NotEmpty Set<StatusVO> vos) {
        return deviceStatusMapper.update(vos);
    }

    @DS(Constants.HISTORY_DB_SCHEME)
    public int insert(@NotEmpty Set<StatusVO> vos, @NotEmpty String tableSuffix) {
        return deviceStatusHistoryMapper.insertBatch(vos, tableSuffix);
    }
}
